package com.cn.common.core.session;

import com.cn.common.core.FastJsonUtils;
import com.cn.common.core.model.Response;
import com.cn.common.core.model.WebStockResponse;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;

/**
 * 会话封装类
 */
public class SessionImpl implements Session {

    /**
     * 绑定对象key
     */
    public static AttributeKey<Object> ATTACHMENT_KEY = AttributeKey.valueOf("ATTACHMENT_KEY");

    /**
     * 实际会话对象
     */
    private Channel channel;

    private Type type = Type.MOBILE;

    public SessionImpl(Channel channel) {
        this.channel = channel;
    }

    @Override
    public Object getAttachment() {
        return channel.attr(ATTACHMENT_KEY).get();
    }

    @Override
    public void setAttachment(Object attachment) {
        channel.attr(ATTACHMENT_KEY).set(attachment);
    }

    @Override
    public void removeAttachment() {
        channel.attr(ATTACHMENT_KEY).remove();
    }

    @Override
    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    @Override
    public void write(Object message) {
        if (type == Type.MOBILE) {
            channel.writeAndFlush(message);
        } else if (type == Type.WEBSOCKET) {
            TextWebSocketFrame tws = new TextWebSocketFrame(FastJsonUtils.toJson(message));
            channel.writeAndFlush(tws);
        }
    }

    @Override
    public boolean isConnected() {
        return channel.isActive();
    }

    @Override
    public void close() {
        channel.close();
    }


}
